<template>
  <div>
    <!-- 导航栏 -->
    <van-nav-bar fixed title="多多买购物车" />
    <!-- 内容展示区 -->
    <van-cell-group inset>
      <van-cell v-for="item in list" :key="item.id">
        <template>
          <div style="display: flex">
            <van-checkbox shape="square" v-model="item.goods_state">
              <van-image
                width="105px"
                height="105px"
                fit="cover"
                radius=".7143rem"
                :src="item.goods_img"
              />
            </van-checkbox>
            <div style="flex: 1; margin-left: 0.7143rem">
              <h4>
                {{ item.goods_name }}
              </h4>
              <div class="r-select">
                <span class="price">￥{{ item.goods_price }}</span>
                <van-stepper v-model="item.goods_count" />
              </div>
            </div>
          </div>
        </template>
      </van-cell>
    </van-cell-group>
    <!-- 提交订单 -->
    <van-submit-bar :price="totalPrice" :button-text="`结算(${count})件`">
      <van-checkbox v-model="chkAll">全选</van-checkbox>
    </van-submit-bar>
  </div>
</template>

<script>
import axios from "axios";
export default {
  data() {
    return {
      // 保存数据源
      list: [],
    };
  },
  created() {
    // 发起请求获取数据
    axios({
      url: "https://www.escook.cn/api/cart",
    })
      .then((res) => {
        // console.log(res);
        //保存数据
        this.list = res.data.list;
      })
      .catch((err) => {
        console.log("请求错误");
      });
  },
  computed: {
    // 总价
    totalPrice() {
      return (
        this.list.reduce((sum, v) => {
          // 选中状态的累加
          if (v.goods_state) {
            sum += v.goods_count * v.goods_price;
          }
          return sum;
        }, 0) * 100
      );
    },
    //全选
    chkAll: {
      get() {
        return this.list.every((v) => v.goods_state);
      },
      set(val) {
        // 全选 state都为true
        this.list.forEach((v) => (v.goods_state = val));
      },
    },
    //结算 数量
    count() {
      return this.list.reduce((sum, v) => {
        // 如果为选中状态
        if (v.goods_state) {
          // 累加数量
          sum += v.goods_count;
        }
        return sum;
      }, 0);
    },
  },
};
</script>

<style scoped lang="less">
.r-select {
  display: flex;
  justify-content: space-around;
  .price {
    font-size: 18px;
    color: red;
  }
}

.van-cell-group {
  margin-top: 3.2857rem;
  margin-bottom: 3.5714rem;
}
</style> 